package com.bys.system.service.impl;

import com.bys.exception.BysOaSystemException;
import com.sun.mail.util.MailSSLSocketFactory;
import org.omg.CORBA.SystemException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

@Service
public class MailService {
    @Resource
    private JavaMailSender javaMailSender;

    /**
     * @param to      收件人
     * @param cc      抄送人
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendMail(String to, String subject, String content) {
        try {
            String host = "smtp.qq.com";
            //        获取当前系统的属性
            Properties properties = System.getProperties();
            properties.setProperty("mail.smtp.host", host);
            properties.setProperty("mail.smtp.auth", "true");
            MailSSLSocketFactory mailssl = new MailSSLSocketFactory();
            mailssl.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", mailssl);
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("1628521608@qq.com", "knmgtuafhispchfg");
                }
            });
            Message message = new MimeMessage(session);
//        设置发件人
            message.setFrom(new InternetAddress("1628521608@qq.com"));
//          设置收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
//        邮件的主题
            message.setSubject(subject);
//        邮件的内容
            message.setContent("<h1>" + content + "</h1>", "text/html;charset=UTF-8");

            Transport.send(message);
        } catch (Exception e) {
            throw new BysOaSystemException("发送失败,请检查邮箱");
        }
    }
}
